<?php
namespace App\Http\Controllers\Api\v1\Recode;
use App\Http\Controllers\Api\BaseController;
use App\Http\Controllers\Api\v1\User\UserinfoController;
use Illuminate\Support\Facades\Input;
use Illuminate\Http\Request;
use  App\Models\Api\Recode;
use  App\Models\Api\Cat;
use  App\Models\Api\RecodeCat;
use  App\Tools\Base\Avatar;
use DB;
// 星盘档案管理控制器
class CatController extends BaseController
{
    private $uid = null;
    /*public function __construct()
    {
            parent::__construct();// 接口调用验证

    }*/
    /**
     * 添加档案袋
     */
    public function add(Request $request)
    {
        $catname = htmlspecialchars($request->input('name'));
        $avatar = htmlspecialchars($request->input('avatar'));

        if(!$catname || mb_strlen($catname,'UTF8') > 10)
        {
            return response()->json(['code'=>10502,'msg'=>'Invalid cat name.']);
        }
        if(!$avatar)
        {
            // 默认档案袋图片随机  1-4
            $avatar = 'uploads/recodecat/'.rand(1,12).'.png';
        }
        $time = time();
        $uid = $request->uid;
        $data = [
            'name'=>$catname,
            'avatar'=>$avatar,
            'status'=>0,
            'create_time'=>$time,
            'last_time'=>$time,
            'uid'=>$uid,
        ];
        $model = new Cat();
        $already = $model->where(['name'=>$catname,'uid'=>$uid]) ->first();
        if(!empty($already))
        {
            return response()->json(['code'=>10503,'msg'=>'This cat name already exist.']);
        }

        $data['id'] = $model->insertGetId($data);

        if(!$data['id'])
        {
            return response()->json(['code'=>10504,'msg'=>'Network error.']);
        }
        return response()->json(['code'=>200,'data'=>$data,'msg'=>'Success.']);
    }
    /**
     * 编辑档案袋
     */
    public function edit(Request $request)
    {
        $catname = $request->input('name', '', 'htmlspecialchars');
        $avatar = htmlspecialchars($request->input('avatar'));
        $id = intval($request->input('id'));
        if(!$id)
        {
            return response()->json(['code'=>10506,'msg'=>'Recode Cat is not exist.']);
        }

        if(trim($catname) == '' || mb_strlen($catname,'utf-8') >= 20)
        {
            return response()->json(['code'=>10507,'msg'=>'Invalid cat name.']);
        }
        if(!$avatar)
        {
            // 默认档案袋图片随机  1-4
            $avatar = 'uploads/recodecat/'.rand(1,12).'.png';
        }
        $uid = $request->uid;
        $data = [
            'name'=>$catname,
            'avatar'=>$avatar,
            'last_time'=>time(),
            'uid'=>$uid,
        ];
        $model = new Cat();
        $rec = $model->where(['id'=>$id,'uid'=>$uid])->first();
        if(empty($rec))
        {
            return response()->json(['code'=>10508,'msg'=>'This recode cat is not exist.']);
        }
        $already = $model->where(['name'=>$catname,['id','=',$id],'uid'=>$uid]) ->first();

        if(!empty($already) && $id )
        {
            return response()->json(['code'=>10509,'msg'=>'This cat name already exist.']);
        }
        if(!$model->where(['id'=>$id])->update($data))
        {
            return response()->json(['code'=>10510,'msg'=>'Network error.']);
        }
        return response()->json(['code'=>200,'data'=>$data,'msg'=>'Success.']);
    }
    /**
     * 删除档案袋
     * 删除用户自己上传的档案袋图片
     * @return mixed
     */
    public function del(Request $request)
    {
        $id = intval($request->input('id'));

        $system_bg = [
            'uploads/recodecat/1.png',
            'uploads/recodecat/2.png',
            'uploads/recodecat/3.png',
            'uploads/recodecat/4.png',
            'uploads/recodecat/5.png',
            'uploads/recodecat/6.png',
            'uploads/recodecat/7.png',
            'uploads/recodecat/8.png',
            'uploads/recodecat/9.png',
            'uploads/recodecat/10.png',
            'uploads/recodecat/11.png',
            'uploads/recodecat/12.png',
        ];
        if(!$id)
        {
            return response()->json(['code'=>10512,'msg'=>'Recode Cat is not exist.']);
        }
         $uid = $request->uid;
        $hasRecode = Recode::from('recode as r')
            ->join('recode_cat as rc','rc.rid','=','r.id','INNER')
            ->join('cat as c','c.id','=','rc.cid','INNER')
            ->where(['r.uid'=>$uid,'rc.cid'=>$id])
            ->get(['r.id','r.uid','rc.cid']);
//        if(!empty($hasRecode))
//        {
//            return response()->json(['code'=>10513,'msg'=>'This recode cat has one or more recode.']);
//        }
        $model = new Cat();
        $data = $model->where(['id'=>$id,'uid'=>$uid]) ->find(1);
        if(empty($data))
        {
            return response()->json(['code'=>10514,'msg'=>'Recode Cat is not exist.']);
        }
        $avatar = $data['avatar'];

        if(!in_array($avatar,$system_bg)) @unlink($avatar);

         $model->where(['id'=>$id,'uid'=>$uid])->delete();
        if(!empty($hasRecode))
        {
            RecodeCat::where(['cid'=>$id])->delete();
        }
        return response()->json(['code'=>200,'msg'=>'DELETE Success.']);
//        DB::startTrans();
//        try{
//            $data = DB::table('cat') -> where(['id'=>$id,'uid'=>$uid]) ->find();
//            if(empty($data))
//            {
//                return response()->json(['code'=>10514,'msg'=>'Recode Cat is not exist.']);
//            }
//            $avatar = $data['avatar'];
//
//            if(!in_array($avatar,$system_bg)) @unlink($avatar);
//
//            DB::table('cat')->where(['id'=>$id,'uid'=>$uid])->delete();
//            if(!empty($hasRecode))
//            {
//                DB::table('recode_cat')->where(['cid'=>$id])->delete();
//            }
//
//            DB::commit();
//            return response()->json(['code'=>200,'msg'=>'DELETE Success.']);
//        } catch (\Exception $e) {
//            // 回滚事务
//            DB::rollback();
//            return response()->json(['code'=>10515,'msg'=>'DELETE Failed.']);
//        }
    }
    /**
     * 获取所有档案袋列表
     */
    public function lists()
    {
         $uid = $request->uid;
        $model =new  Cat();
        $data = $model->where(['uid'=>$uid,'status'=>0])->orderBy('id','DESC') ->get(['id','name','status','avatar','count','uid']);

        return response()->json(['code'=>200,'data'=>$data,'msg'=>'Success']);
    }
    /**
     * 获取档案袋中的所有档案
     */
    public function recodes(Request $request)
    {
        $cid = intval($request->input('cid'));
        if(!$cid)
        {
            return response()->json(['code'=>10518,'msg'=>'Recode Cat is not exist.']);
        }
         $uid = $request->uid;
        $data = Recode::from('recode as r')
            ->join('recode_cat as rc','rc.rid','=','r.id','INNER')
            ->join('cat as c','c.id','=','rc.cid','INNER')
            ->where(['r.uid'=>$uid,'rc.cid'=>$cid,'r.status'=>1])
            ->orderBy('id','DESC')
            ->get(['r.id','r.uid','rc.cid']);

        return response()->json(['code'=>200,'data'=>$data,'msg'=>'Success']);
    }
     public function recodelists(Request $request)
    {

        $data = Recode::from('recode as r')
            ->join('recode_astro as ra','r.id','=','ra.rid','INNER')
            ->where(['uid'=>$request->uid,'r.status'=>1])
            ->select(['r.id','r.name','r.type','r.year','r.month','r.day','r.hour','r.minute','r.timezone','birth_country','birth_province','birth_city','live_country','live_province','live_city','comments','isself','long_deg','long_min','ew','lat_deg','lat_min','ns','avatar','is_summer','uid','aid','sun','moon','merc','venu','mars','jupi','satu','non','lili','juno','asc','mc'])->get();

    return response()->json(['code'=>200,'data'=>$data,'msg'=>'Success']);
    }

    /**
     * 添加档案袋背景
     */
    public function avatar($dir = 'uploads')
    {
        $Avatar = new Avatar();

        return $Avatar->upload($dir);
    }
    /**
     * 获取档案袋背景图地址列表
     */
    public function bg_lists()
    {
        $system_bg = [
            'uploads/recodecat/1.png',
            'uploads/recodecat/2.png',
            'uploads/recodecat/3.png',
            'uploads/recodecat/4.png',
            'uploads/recodecat/5.png',
            'uploads/recodecat/6.png',
            'uploads/recodecat/7.png',
            'uploads/recodecat/8.png',
            'uploads/recodecat/9.png',
            'uploads/recodecat/10.png',
            'uploads/recodecat/11.png',
            'uploads/recodecat/12.png',
        ];
        return response()->json(['code'=>200,'data'=>$system_bg,'msg'=>'Success.']);
    }
}
